import datetime
import requests
import GlobalVariable
import my_influxdb3
import my_JDServiceAPI
import NoticePush
import NoticeTemplate
from urllib.parse import quote


# 获取当天时间和当天积分
def todayPointIncome():
    today_total_point = 0
    today_date = ""
    res = requests.get(GlobalVariable.jd_base_url + "todayPointIncome", headers=GlobalVariable.headers)
    if res.status_code == 200:
        res_json = res.json()
        result = res_json["result"]
        today_total_point = result["todayTotalPoint"]
        todayDate = result["todayDate"]
        today_date = datetime.datetime.strptime(todayDate, "%Y%m%d").strftime("%Y年%m月%d日")
    else:
        errorMessage = res.json()['error']['message']
        print(errorMessage)
        print("Request todayPointIncome failed!")
    GlobalVariable.final_result["today_date"] = today_date
    GlobalVariable.final_result["today_total_point"] = str(today_total_point)
    return today_total_point


# 获取今日总积分
def pinTotalAvailPoint():
    total_avail_point = 0
    res = requests.get(GlobalVariable.jd_base_url + "pinTotalAvailPoint", headers=GlobalVariable.headers)
    if res.status_code == 200:
        res_json = res.json()
        result = res_json["result"]
        total_avail_point = result["totalAvailPoint"]
    else:
        print("Request pinTotalAvailPoint failed!")
    GlobalVariable.final_result["total_avail_point"] = str(total_avail_point)
    return total_avail_point


# 路由账户信息
def routerAccountInfo(mac):
    params = {
        "mac": mac,
    }
    res = requests.get(GlobalVariable.jd_base_url + "routerAccountInfo", params=params, headers=GlobalVariable.headers)
    if res.status_code == 200:
        res_json = res.json()
        result = res_json["result"]
        accountInfo = result["accountInfo"]
        mac = accountInfo["mac"]
        amount = accountInfo["amount"]
        bindAccount = accountInfo["bindAccount"]
        GlobalVariable.service_headers["pin"] = quote(bindAccount)
        recentExpireAmount = accountInfo["recentExpireAmount"]
        recentExpireTime = accountInfo["recentExpireTime"]
        recentExpireTime_str = datetime.datetime.fromtimestamp(recentExpireTime / 1000).strftime("%Y-%m-%d %H:%M:%S")
        account_info = {"amount": str(amount), "bindAccount": str(bindAccount),
                        "recentExpireAmount": str(recentExpireAmount), "recentExpireTime": recentExpireTime_str}
        index = GlobalVariable.findALocation(mac)
        if index != -1:
            point_info = GlobalVariable.final_result["pointInfos"][index]
            point_info.update(account_info)
        else:
            print("Find mac failure!")
    else:
        print("Request routerAccountInfo failed!")


# 路由活动信息
def routerActivityInfo(mac):
    params = {
        "mac": mac,
    }
    res = requests.get(GlobalVariable.jd_base_url + "router:activityInfo", params=params,
                       headers=GlobalVariable.headers)
    if res.status_code == 200:
        res_json = res.json()
        result = res_json["result"]
        # finishActivity = result["finishActivity"]
        if result["routerUnderwayResult"] is None:
            exit
        else:
            totalIncomeValue = result["routerUnderwayResult"]["totalIncomeValue"]
            satisfiedTimes = result["routerUnderwayResult"]["satisfiedTimes"]
            activity_info = {"mac": mac, "totalIncomeValue": totalIncomeValue, "satisfiedTimes": satisfiedTimes}
            index = GlobalVariable.findALocation(mac)
            if index != -1:
                point_info = GlobalVariable.final_result["pointInfos"][index]
                point_info.update(activity_info)
            else:
                print("Request routerActivityInfo failed!")


# 收益信息
def todayPointDetail(mac):
    params = {
        "sortField": "today_point",
        "sortDirection": "DESC",
        "pageSize": "30",
        "currentPage": "1"
    }

    my_JDServiceAPI.getControlDevice(mac, 2)











# region 通知结果

# 结果显示
def resultDisplay():
    today_date = GlobalVariable.final_result["today_date"]
    today_total_point = GlobalVariable.final_result["today_total_point"]
    title = today_date + "到账积分:" + today_total_point
    if GlobalVariable.final_result.get("todayDate") is None:
        push("信息获取失败,无权限", "请检查wskey是否有效")
        return
    todayDate = GlobalVariable.final_result["todayDate"]
    total_avail_point = GlobalVariable.final_result["total_avail_point"]
    totalRecord = GlobalVariable.final_result["totalRecord"]
    pointInfos = GlobalVariable.final_result["pointInfos"]
    content = ""
    point_infos = ""
    bindAccount = ""
    # 更新检测
    if GlobalVariable.final_result.get("updates_version"):
        content = content + "**JDRouterPush更新提醒:**" \
                  + "\n```\n最新版：" + GlobalVariable.final_result["updates_version"] \
                  + "  当前版本：" + GlobalVariable.version
        if GlobalVariable.final_result.get("update_log"):
            content = content + "\n" + GlobalVariable.final_result["update_log"] + "\n```"
    if GlobalVariable.final_result.get("announcement"):
        content = content + "\n> " + GlobalVariable.final_result["announcement"] + " \n\n"
    for pointInfo in pointInfos:
        mac = pointInfo["mac"]
        todayPointIncome = pointInfo.get("todayPointIncome","获取失败")
        allPointIncome = pointInfo.get("allPointIncome","获取失败")
        amount = pointInfo.get("amount","获取失败")
        bindAccount = pointInfo.get("bindAccount","获取失败")
        recentExpireAmount = pointInfo.get("recentExpireAmount","获取失败")
        recentExpireTime = pointInfo.get("recentExpireTime","获取失败")
        satisfiedTimes = ""
        if pointInfo.get("satisfiedTimes"):
            satisfiedTimes = pointInfo["satisfiedTimes"]

        point_infos += "\n" + "- " + GlobalVariable.device_name.get(str(mac[-6:]), GlobalVariable.device_list[mac][
            "device_name"]) + "==>" \
                       + "\n    - 今日积分：" + str(todayPointIncome) \
                       + "\n    - 可用积分：" + str(amount) \
                       + "\n    - 总收积分：" + str(allPointIncome)
        if satisfiedTimes != "":
            point_infos += "\n    - 累计在线：" + str(satisfiedTimes) + "天"
        if pointInfo.get("runInfo"):
            point_infos += "\n    - 当前网速：" + pointInfo["speed"] \
                           + "\n    - 当前IP：" + pointInfo["wanip"] \
                           + "\n    - 当前模式：" + pointInfo["model"] \
                           + "\n    - 固件版本：" + pointInfo["rom"]
        if pointInfo.get("pluginInfo"):
            point_infos += "\n    - 插件状态：" + pointInfo["status"] \
                           + "\n    - 缓存大小：" + pointInfo["cache_size"]
        point_infos += "\n    - 在线时间：" + pointInfo.get("onlineTime", "---") \
                       + "\n    - 最近到期积分：" + str(recentExpireAmount) \
                       + "\n    - 最近到期时间：" + recentExpireTime \
                       + "\n    - 最近" + str(GlobalVariable.records_num) + "条记录："
        pointRecords = pointInfo["pointRecords"]
        if pointInfo.get("pointRecords") is not None:
            for pointRecord in pointRecords:
                recordType = pointRecord["recordType"]
                recordType_str = ""
                if recordType == 1:
                    recordType_str = "积分收入："
                else:
                    recordType_str = "积分支出："
                pointAmount = pointRecord["pointAmount"]
                createTime = pointRecord["createTime"]
                point_infos = point_infos + "\n        - " + \
                              createTime + "  " + recordType_str + str(pointAmount)
    notifyContentJson = {"content": content, "date": todayDate, "total_today": today_total_point,
                         "avail_today": total_avail_point, "account": bindAccount, "devicesCount": totalRecord,
                         "detail": point_infos}
    print("节点信息",notifyContentJson)
    push(title,notifyContentJson)

def push(title,content):

    if isinstance(content,str):
        markdownContent = content
        normalContent = content
    else:
        # mk模板
        markdownContent = NoticeTemplate.markdownTemplate().format(**content)
        # 普通模板
        normalContent = NoticeTemplate.normalTemplate().format(**content)

    NoticePush.server_push(title, markdownContent.replace("- ***", "```"))
    NoticePush.push_plus(title, markdownContent)
        # print("标题->", title)
        # print("内容->\n", markdownContent)


    NoticePush.telegram_bot(title, normalContent)
    NoticePush.bark(title, normalContent)
    NoticePush.enterprise_wechat(title, normalContent)


    # 信息输出测试
    print("标题->", title)
    # print("内容->\n", normalContent)

# endregion

# 处理IP
def handleIP(wanip, ipSegment):
    print("当前IP:%s ===> 期待IP:%s" % (wanip, ipSegment))
    wanip_list = wanip.split(".")
    ipSegment_list = ipSegment.split(".")
    for wanip, ipSegment in zip(wanip_list, ipSegment_list):
        if wanip == ipSegment or ipSegment == "*":
            pass
        else:
            if "<" in ipSegment:
                ip = ipSegment.split("<")[1]
                if int(wanip) >= int(ip):
                    return False
            elif ">" in ipSegment:
                ip = ipSegment.split(">")[1]
                if int(wanip) <= int(ip):
                    return False
            else:
                return False
    return True





# 主操作
def main():

        # if GlobalVariable.RECORDSNUM.isdigit():
        #     GlobalVariable.records_num = int(GlobalVariable.RECORDSNUM)
        macs= GlobalVariable.macs.split('&')
        for mac in macs:
            GlobalVariable.final_result={}
            todayPointDetail(mac)
            client = my_influxdb3.creat_client()
            pointInfos= GlobalVariable.final_result["pointInfos"]
            speed=pointInfos.get('speed')
            cpu=pointInfos.get('cpu_num')
            mem=pointInfos.get('mem_num')

            # onlineTime=pointInfos.get('onlineTime')

            upload_num=pointInfos.get('upload_num')
            download_num=pointInfos.get('download_num')
            # 传一个tag  多个file时要传一个集合
            my_influxdb3.add(client, "JD", mac, [{"upload_num":upload_num},
                                                 {"download_num":download_num},
                                                 {"cpu_num":cpu},
                                                 {"mem_num":mem}])





# endregion

def runTest(i):
    if i > 10:
        return
    # try:
    if GlobalVariable.WSKEY is None or GlobalVariable.WSKEY.strip() == '':
        print("未获取到环境变量'WSKEY'，执行中止")
        return
    GlobalVariable.headers["wskey"] = GlobalVariable.WSKEY
    GlobalVariable.service_headers["tgt"] = GlobalVariable.WSKEY
    main()
    # except Exception as e:
    #     print("出现错误：", e)
    #     print("准备重新执行...")
    #     time.sleep(60)
    #     runTest(++i)


# 读取配置文件
if __name__ == '__main__':
    runTest(0)

